/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.apps;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;

import org.apache.xmlbeans.XmlCursor;

import cgl.narada.wsinfra.deployment.Filter;
import cgl.narada.wsinfra.deployment.FilterPipeline;
import cgl.narada.wsinfra.deployment.FilterPipelineFactory;
import cgl.narada.wsinfra.deployment.NetworkSubstrate;
import cgl.narada.wsinfra.deployment.ServiceMessageListener;
import cgl.narada.wsinfra.deployment.impl.NBNetworkSubstrate;
import cgl.narada.wsinfra.exception.DeploymentException;
import cgl.narada.wsinfra.exception.MessageFlowException;
import cgl.narada.wsinfra.exception.ProcessingException;
import cgl.narada.wsinfra.schemas.addressing.ActionDocument;
import cgl.narada.wsinfra.schemas.addressing.EndpointReferenceType;
import cgl.narada.wsinfra.schemas.addressing.FromDocument;
import cgl.narada.wsinfra.schemas.addressing.RelatesToDocument;
import cgl.narada.wsinfra.schemas.soap.EnvelopeDocument;
import cgl.narada.wsinfra.util.QNameLocator;
import cgl.narada.wsinfra.util.SoapEnvelopeConversion;
import cgl.narada.wsinfra.util.SoapMessageAlteration;
import cgl.narada.wsinfra.util.SoapPrinter;
import cgl.narada.wsinfra.wsa.WsaEnvelopeCreator;
import cgl.narada.wsinfra.wsa.WsaEprCreator;
import cgl.narada.wsinfra.wsa.WsaProcessingFactory;
import cgl.narada.wsinfra.wsrm.WsrmQNames;

public class WsrmEndpoint implements ServiceMessageListener {
  private NetworkSubstrate networkSubstrate;
  private FilterPipelineFactory filterPipelineFactory;
  private FilterPipeline filterPipeline;
  private WsaEprCreator wsaEprCreator;
  private WsaEnvelopeCreator wsaEnvelopeCreator;
  private SoapEnvelopeConversion soapEnvelopeConversion;
  private SoapMessageAlteration soapMessageAlteration;
  private Filter loggingFilter;
  private Filter counterFilter;
  private Filter wsrmSourceFilter;
  private Filter wsrmSinkFilter;
  private int tracker;
  private String moduleName = "WsrmEndpoint: ";

  public WsrmEndpoint(String address, Properties props, String configInfo) 
    throws DeploymentException {
    filterPipelineFactory =  FilterPipelineFactory.getInstance();
    filterPipeline = filterPipelineFactory.newFilterPipeline("WsrmPipeline");
    
    wsrmSinkFilter = new WsrmSinkFilter(configInfo, address);
    wsrmSourceFilter = new WsrmSourceFilter(configInfo, address);
    loggingFilter = new LoggingFilter();
    counterFilter = new CounterFilter();

    filterPipeline.addFilter(wsrmSinkFilter);
    filterPipeline.addFilter(wsrmSourceFilter);
    //filterPipeline.addFilter(counterFilter);
    //filterPipeline.addFilter(loggingFilter);

    /*System.out.println(moduleName + "Configured FilterPipeline" + 
      "\n\tWsrmSinkFilter=" +  
      wsrmSinkFilter.getPositionInFilterPipeline() +
      "\n\tWsrmSourceFilter=" +
      wsrmSourceFilter.getPositionInFilterPipeline() +
      "\n\tCounterFilter=" + 
      counterFilter.getPositionInFilterPipeline() +
      "\n\tLoggingFilter=" +
      loggingFilter.getPositionInFilterPipeline()   ); */
    
    networkSubstrate = new NBNetworkSubstrate();
    networkSubstrate.configureNetworking(props);
    
    networkSubstrate.registerPipeline(filterPipeline);
    filterPipeline.registerNetworkSubstrate(networkSubstrate);

    wsaEprCreator = WsaProcessingFactory.getWsaEprCreator();
    wsaEnvelopeCreator = WsaProcessingFactory.getWsaEnvelopeCreator();

    soapEnvelopeConversion = SoapEnvelopeConversion.getInstance();
    soapMessageAlteration = SoapMessageAlteration.getInstance();
  }

  public void onMessage(SOAPMessage soapMessage) {
    System.out.println(moduleName + "Received SOAP Message from the " +
		       "underlying infrastructure");
    printSoapMessage(soapMessage);
  }

  public void onException(Exception exception) {


  }

  public void changeFilterOrder() throws DeploymentException {
    int position = loggingFilter.getPositionInFilterPipeline() ;
    if (position == 0) {
      filterPipeline.moveFilter(loggingFilter, 1);
    } 

    if (position == 1) {
      filterPipeline.moveFilter(loggingFilter, 0);
    } 
    
  }



  public String createLinkTo(Properties props, String linkType) 
    throws DeploymentException { 
    if (networkSubstrate == null) {
      System.out.println(moduleName + "The network substrate is null");
    }
    String linkId = 
      ( (NBNetworkSubstrate)networkSubstrate).createLinkTo(props, linkType);
    return linkId;
  }


  public void sendSOAPMessage(SOAPMessage soapMessage) 
    throws DeploymentException, MessageFlowException, ProcessingException {
    filterPipeline.processMessageFromApplication(soapMessage); 
  }

  public SOAPMessage createSOAPMessage(String source, String sink, 
				       boolean lastMessage) {
    EndpointReferenceType sourceEpr = wsaEprCreator.createEpr(source);
    EndpointReferenceType sinkEpr = wsaEprCreator.createEpr(sink);

    FromDocument from = FromDocument.Factory.newInstance();
    from.setFrom(sourceEpr);
    ActionDocument action = null;
    RelatesToDocument relatesTo = null;

    EnvelopeDocument envelopeDocument = 
      wsaEnvelopeCreator.createSoapEnvelope(sinkEpr, from, action, relatesTo);
    QName qname = new QName("http://www.naradabrokering.org",
			    "Application-Content");
    XmlCursor bodyCursor = 
      envelopeDocument.getEnvelope().getBody().newCursor();
    tracker++;
    String value = "Tracker :" + tracker;
    bodyCursor.toNextToken();
    bodyCursor.insertElementWithText(qname, value);
    bodyCursor.dispose();


    if (lastMessage) {
      QName qNameNbx = WsrmQNames.getInstance().getLastMessageNBX();
      String valueNbx = "true";
      boolean added =soapMessageAlteration.addToSoapHeader(envelopeDocument, 
							   qNameNbx, valueNbx);
      if (added) {
	System.out.println(moduleName + "LAST MESSAGE SUCCESS");
      }
    }



    SOAPMessage soapMessage = null;
    try {
      soapMessage =  soapEnvelopeConversion.getSOAPMessage(envelopeDocument);
    } catch (ProcessingException ex) {
      String errorReport ="Problems converting to javax.xml.SOAPMessage\n"
	+ ex.toString();
      System.out.println(errorReport);
    }
    return soapMessage;
    
  }


  public boolean setLastMessage(SOAPMessage soapMessage) {
    EnvelopeDocument envelopeDocument = null;

    try {
      envelopeDocument = 
	soapEnvelopeConversion.getEnvelopeDocument(soapMessage);
    }  catch (ProcessingException ex) {
      String errorReport ="Problems converting to javax.xml.SOAPMessage\n"
	+ ex.toString();
      System.out.println(errorReport);
    }

    if (envelopeDocument == null) {
      return false;
    }
    
    //XmlCursor headerCursor = envelopeDocument.getEnvelope().getHeader().newCursor();
    //String wsrmxUri = "http://www.naradabrokering.org/wsrmExtension";
    //QName qName = new QName(wsrmxUri, "LastMessage");
    //headerCursor.toNextToken();
    //headerCursor.insertElementWithText(qName, "true");
    //headerCursor.dispose();
    
    QName qName = WsrmQNames.getInstance().getLastMessageNBX();
    String value = "true";
    boolean added = soapMessageAlteration.addToSoapHeader(envelopeDocument, 
							  qName, value);
    if (added) {
      System.out.println(moduleName + "Addition Successful");
    }
    
 
    System.out.println(moduleName + "The Modified SOAP Envelope is \n" +
		       envelopeDocument.toString() );

    //qName = new QName(wsrmxUri, "LastMessage2");
    boolean removed = 
      soapMessageAlteration.removeFromSoapHeader(envelopeDocument, qName);
    
    if (removed) {
      System.out.println(moduleName + "The Removal was Successful");
    }

    XmlCursor headerCursor = 
      envelopeDocument.getEnvelope().getHeader().newCursor();
    QNameLocator qNameLocator = QNameLocator.getInstance();
    boolean found = qNameLocator.locateQName(headerCursor, qName);

    if (found) {
      System.out.println(moduleName + 
			 "Last Message=" + headerCursor.getTextValue());
      headerCursor.removeXml();
      headerCursor.dispose();
    }


    System.out.println(moduleName + "The Modified SOAP Envelope is \n" +
		       envelopeDocument.toString() );
    return true;
  }

  public void printSoapMessage(SOAPMessage soapMessage) {
    String soapMsg = null;
    try {
      soapMsg = SoapPrinter.getStringRepresentation(soapMessage);
    } catch (Exception e) {
      System.out.println(moduleName + "Problems printing SOAPMessage"); 
    }
    System.out.println(soapMsg);
  }


  public static void main(String[] args) {
    if (args.length != 3) {
      System.out.println("Usage: java cgl.narada.wsinfra.apps.WsrmEndpoint " +
			 "[hostname] [TCPServerPort] [WsrmConfigFileLocation]");
      System.exit(0);
    }

    String hostname = args[0];
    String port = args[1];
    String wsrmConfigFile = args[2];
    Properties props = new Properties();
    props.put("TCPServerPort", port);
    
    BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer tok;
    String cmd;

    try {
      String address = "tcp://" + hostname + ":" + port;
      WsrmEndpoint endpoint = new WsrmEndpoint(address, props, wsrmConfigFile);
      System.out.println("Listening to TCP communications on port [" + port 
			 + "]. ");
      while (true) {
      	cmd = r.readLine();
	
	if(cmd.startsWith("h")) {
	  System.out.println("Create Link           -> cr hostname portNum ");
	  System.out.println("Send Data [from] [to] -> s  [source] [sink]" );
	}
	
	if (cmd.startsWith("cr")) {
	  tok = new StringTokenizer(cmd, " ");
	  tok.nextToken(); /* skipping the token "cr" */
	  Properties linkProps = new Properties();
	  linkProps.put("hostname", tok.nextToken());
	  linkProps.put("portnum", tok.nextToken());
	  String _linkId = endpoint.createLinkTo(linkProps, "tcp");
	  System.out.println("Created link with id => " + _linkId); 
	} /** end create link */
	
	if (cmd.startsWith("s")) {
	  tok = new StringTokenizer(cmd, " ");
	  tok.nextToken(); /* skipping the token "s" */
	  String source = tok.nextToken();
	  String sink = tok.nextToken();
	  boolean lastMessage = false;
	  if (tok.hasMoreTokens() ) {
	    lastMessage = true;
	  }
	  
	  SOAPMessage soapMessage = endpoint.createSOAPMessage(source, sink,
							       lastMessage);
	  //endpoint.printSoapMessage(soapMessage);
	  endpoint.sendSOAPMessage(soapMessage);
	}


	if (cmd.startsWith("o")) {
	  endpoint.changeFilterOrder();
	}

	if (cmd.startsWith("a")) {
	  String source = "Romeo@Shakespere.org";
	  String sink = "Juliet@Tragedy.org";
	  SOAPMessage soapMessage = endpoint.createSOAPMessage(source, sink,
							       true);
	  
	  boolean success = endpoint.setLastMessage(soapMessage);
	  //System.out.println(moduleName + "We have " + success? "NOT": " " 
	}
	
      } /* end while(true) */

    }catch (Exception ioe) {
      ioe.printStackTrace();
    } /* end try-catch */
  }/*end main() */

}
